<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <SearchForm
      v-model="searchForm"
      :inline="true"
      label-width="80px"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="订单号">
        <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="会员等级">
        <el-select v-model="searchForm.levelId" placeholder="请选择会员等级" clearable>
          <el-option 
            v-for="level in memberLevels" 
            :key="level.id" 
            :label="level.name" 
            :value="level.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="待支付" value="PENDING" />
          <el-option label="已支付" value="PAID" />
          <el-option label="已取消" value="CANCELLED" />
          <el-option label="已退款" value="REFUNDED" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </SearchForm>
    
    <!-- 统计卡片 -->
    <div class="stats-container">
      <StatCard
        title="订单总数"
        :value="statistics.totalOrders || 0"
        icon="Tickets"
        type="primary"
        :trend="statistics.orderGrowth"
      />
      <StatCard
        title="今日订单"
        :value="statistics.todayOrders || 0"
        icon="Tickets"
        type="success"
      />
      <StatCard
        title="订单总额"
        :value="statistics.totalAmount || 0"
        icon="Wallet"
        type="warning"
      />
      <StatCard
        title="支付率"
        :value="statistics.paymentRate || 0"
        icon="DataLine"
        type="info"
        suffix="%"
      />
    </div>
    
    <!-- 图表区域 -->
    <div class="chart-container">
      <div class="chart-row">
        <!-- 订单趋势图 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">订单趋势</div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="orderTrendChartRef"
              :options="orderTrendChartOptions"
              :loading="chartLoading"
              height="300px"
            />
          </div>
        </div>
        
        <!-- 会员等级销售分布 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">会员等级销售分布</div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="levelSalesChartRef"
              :options="levelSalesChartOptions"
              :loading="chartLoading"
              height="300px"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 会员订单表格 -->
    <Card title="会员订单列表">
      <template #extra>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </template>
      
      <CommonTable
        ref="tableRef"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #status="{ row }">
          <el-tag :type="getOrderStatusColor(row.status)">
            {{ getOrderStatusLabel(row.status) }}
          </el-tag>
        </template>
        
        <template #amount="{ row }">
          <span>¥{{ row.amount }}</span>
        </template>
        
        <template #levelName="{ row }">
          <el-tag type="warning">{{ row.levelName }}</el-tag>
        </template>
        
        <template #action="{ row }">
          <el-button type="primary" link @click="handleView(row)">
            <el-icon><View /></el-icon>
            查看详情
          </el-button>
          <el-button 
            v-if="row.status === 'PENDING'"
            type="primary" 
            link 
            @click="handleConfirmPayment(row)"
          >
            <el-icon><Check /></el-icon>
            确认支付
          </el-button>
          <el-button 
            v-if="row.status === 'PAID'"
            type="primary" 
            link 
            @click="handleRefund(row)"
          >
            <el-icon><RefreshLeft /></el-icon>
            退款
          </el-button>
          <el-button 
            v-if="row.status !== 'PAID'"
            type="danger" 
            link 
            @click="handleDelete(row)"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </CommonTable>
    </Card>
    
    <!-- 订单详情对话框 -->
    <CommonDialog
      v-model="detailVisible"
      title="订单详情"
      width="600px"
      :show-footer="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ orderDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ orderDetail.username }}</el-descriptions-item>
        <el-descriptions-item label="会员等级">{{ orderDetail.levelName }}</el-descriptions-item>
        <el-descriptions-item label="金额">
          <span>¥{{ orderDetail.amount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ orderDetail.paymentMethod || '-' }}</el-descriptions-item>
        <el-descriptions-item label="交易号">{{ orderDetail.transactionNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getOrderStatusColor(orderDetail.status)">
            {{ getOrderStatusLabel(orderDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ orderDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ orderDetail.paymentTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ orderDetail.startTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="到期时间">{{ orderDetail.endTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ orderDetail.remark || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </CommonDialog>
    
    <!-- 确认支付对话框 -->
    <CommonDialog
      v-model="paymentVisible"
      title="确认支付"
      width="500px"
      @confirm="handleConfirmPaymentSubmit"
      @cancel="handleCancelPayment"
    >
      <el-form
        ref="paymentFormRef"
        :model="paymentForm"
        :rules="paymentFormRules"
        label-width="100px"
      >
        <el-form-item label="订单号">
          <span>{{ currentOrder.orderNo }}</span>
        </el-form-item>
        <el-form-item label="用户名">
          <span>{{ currentOrder.username }}</span>
        </el-form-item>
        <el-form-item label="金额">
          <span>¥{{ currentOrder.amount }}</span>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="paymentForm.paymentMethod" placeholder="请选择支付方式">
            <el-option label="微信支付" value="WECHAT" />
            <el-option label="支付宝" value="ALIPAY" />
            <el-option label="银行卡" value="BANK_CARD" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易号" prop="transactionNo">
          <el-input v-model="paymentForm.transactionNo" placeholder="请输入交易号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="paymentForm.remark" 
            type="textarea" 
            placeholder="请输入备注" 
            :rows="3" 
          />
        </el-form-item>
      </el-form>
    </CommonDialog>
    
    <!-- 退款对话框 -->
    <CommonDialog
      v-model="refundVisible"
      title="退款"
      width="500px"
      @confirm="handleRefundSubmit"
      @cancel="handleCancelRefund"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundFormRules"
        label-width="100px"
      >
        <el-form-item label="订单号">
          <span>{{ currentOrder.orderNo }}</span>
        </el-form-item>
        <el-form-item label="用户名">
          <span>{{ currentOrder.username }}</span>
        </el-form-item>
        <el-form-item label="退款金额">
          <span>¥{{ currentOrder.amount }}</span>
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input 
            v-model="refundForm.reason" 
            type="textarea" 
            placeholder="请输入退款原因" 
            :rows="3" 
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="refundForm.remark" 
            type="textarea" 
            placeholder="请输入备注" 
            :rows="3" 
          />
        </el-form-item>
      </el-form>
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMemberOrderList, getMemberOrderDetail, deleteMemberOrder, batchDeleteMemberOrders, confirmPayment, refundOrder, getMemberStatistics, getMemberLevelList } from '@/api/member'
import { useTable } from '@/hooks/useTable'
import { useForm } from '@/hooks/useForm'
import { useDialog } from '@/hooks/useDialog'

// 表格列配置
const columns = [
  {
    type: 'selection',
    width: '55'
  },
  {
    prop: 'orderNo',
    label: '订单号',
    width: '180'
  },
  {
    prop: 'username',
    label: '用户名',
    minWidth: '120'
  },
  {
    prop: 'levelName',
    label: '会员等级',
    width: '120',
    slot: 'levelName'
  },
  {
    prop: 'amount',
    label: '金额',
    width: '120',
    slot: 'amount'
  },
  {
    prop: 'paymentMethod',
    label: '支付方式',
    width: '120'
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    slot: 'status'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '180',
    sortable: 'custom'
  },
  {
    prop: 'paymentTime',
    label: '支付时间',
    width: '180'
  },
  {
    prop: 'action',
    label: '操作',
    width: '200',
    slot: 'action',
    fixed: 'right'
  }
]

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  username: '',
  levelId: '',
  status: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  totalOrders: 0,
  todayOrders: 0,
  totalAmount: 0,
  paymentRate: 0,
  orderGrowth: 0
})

// 图表相关
const orderTrendChartRef = ref(null)
const levelSalesChartRef = ref(null)
const chartLoading = ref(false)
const orderTrendChartOptions = ref({})
const levelSalesChartOptions = ref({})

// 表格相关
const {
  tableData,
  loading,
  pagination,
  selectedRows,
  loadData,
  handleSelectionChange,
  handleSortChange,
  handleSizeChange,
  handleCurrentChange
} = useTable(getMemberOrderList, {
  defaultParams: searchForm,
  immediate: false
})

// 表单相关
const paymentFormRules = {
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  transactionNo: [
    { required: true, message: '请输入交易号', trigger: 'blur' }
  ]
}

const refundFormRules = {
  reason: [
    { required: true, message: '请输入退款原因', trigger: 'blur' }
  ]
}

const {
  formData: paymentForm,
  formRef: paymentFormRef,
  submitting: paymentSubmitting,
  validateForm: validatePaymentForm,
  submitForm: submitPaymentForm
} = useForm({
  paymentMethod: '',
  transactionNo: '',
  remark: ''
}, handleConfirmPaymentSubmit)

const {
  formData: refundForm,
  formRef: refundFormRef,
  submitting: refundSubmitting,
  validateForm: validateRefundForm,
  submitForm: submitRefundForm
} = useForm({
  reason: '',
  remark: ''
}, handleRefundSubmit)

// 对话框相关
const {
  visible: detailVisible,
  showDialog: showDetailDialog,
  hideDialog: hideDetailDialog
} = useDialog()

const {
  visible: paymentVisible,
  showDialog: showPaymentDialog,
  hideDialog: hidePaymentDialog
} = useDialog()

const {
  visible: refundVisible,
  showDialog: showRefundDialog,
  hideDialog: hideRefundDialog
} = useDialog()

// 其他变量
const tableRef = ref(null)
const memberLevels = ref([])
const orderDetail = reactive({})
const currentOrder = reactive({})

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const response = await getMemberStatistics()
    if (response) {
      Object.assign(statistics, response)
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 获取会员等级列表
const getMemberLevelsData = async () => {
  try {
    const response = await getMemberLevelList({ status: 'ACTIVE' })
    if (response && response.data) {
      memberLevels.value = response.data.records || response.data || []
    }
  } catch (error) {
    console.error('获取会员等级列表失败', error)
  }
}

// 获取图表数据
const getChartData = async () => {
  try {
    chartLoading.value = true
    
    // 模拟获取订单趋势数据
    const orderTrendData = {
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '订单数量',
          type: 'line',
          smooth: true,
          data: [50, 65, 45, 80, 60, 90, 75],
          areaStyle: {
            color: 'rgba(24, 144, 255, 0.2)'
          },
          lineStyle: {
            color: '#1890ff'
          }
        }
      ]
    }
    
    // 模拟获取会员等级销售分布数据
    const levelSalesData = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '会员等级销售分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 335, name: '普通会员' },
            { value: 310, name: '高级会员' },
            { value: 234, name: 'VIP会员' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    orderTrendChartOptions.value = orderTrendData
    levelSalesChartOptions.value = levelSalesData
  } catch (error) {
    console.error('获取图表数据失败', error)
  } finally {
    chartLoading.value = false
  }
}

// 获取订单状态颜色
const getOrderStatusColor = (status) => {
  const colors = {
    PENDING: 'warning',
    PAID: 'success',
    CANCELLED: 'info',
    REFUNDED: 'danger'
  }
  return colors[status] || 'info'
}

// 获取订单状态标签
const getOrderStatusLabel = (status) => {
  const labels = {
    PENDING: '待支付',
    PAID: '已支付',
    CANCELLED: '已取消',
    REFUNDED: '已退款'
  }
  return labels[status] || status
}

// 处理搜索
const handleSearch = () => {
  loadData({
    ...searchForm,
    startTime: searchForm.dateRange?.[0],
    endTime: searchForm.dateRange?.[1]
  })
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    username: '',
    levelId: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 处理查看
const handleView = async (row) => {
  try {
    const response = await getMemberOrderDetail(row.id)
    if (response) {
      Object.assign(orderDetail, response)
      showDetailDialog()
    }
  } catch (error) {
    console.error('获取订单详情失败', error)
  }
}

// 处理确认支付
const handleConfirmPayment = (row) => {
  Object.assign(currentOrder, row)
  paymentForm.paymentMethod = ''
  paymentForm.transactionNo = ''
  paymentForm.remark = ''
  showPaymentDialog()
}

// 处理确认支付提交
async function handleConfirmPaymentSubmit() {
  try {
    await confirmPayment(currentOrder.id, paymentForm)
    ElMessage.success('确认支付成功')
    hidePaymentDialog()
    loadData()
    getStatisticsData()
  } catch (error) {
    console.error('确认支付失败', error)
  }
}

// 处理取消支付
const handleCancelPayment = () => {
  hidePaymentDialog()
}

// 处理退款
const handleRefund = (row) => {
  Object.assign(currentOrder, row)
  refundForm.reason = ''
  refundForm.remark = ''
  showRefundDialog()
}

// 处理退款提交
async function handleRefundSubmit() {
  try {
    await refundOrder(currentOrder.id, refundForm)
    ElMessage.success('退款成功')
    hideRefundDialog()
    loadData()
    getStatisticsData()
  } catch (error) {
    console.error('退款失败', error)
  }
}

// 处理取消退款
const handleCancelRefund = () => {
  hideRefundDialog()
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除订单 "${row.orderNo}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMemberOrder(row.id)
      ElMessage.success('删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('删除失败', error)
    }
  }).catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的订单')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${ids.length} 个订单吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await batchDeleteMemberOrders(ids)
      ElMessage.success('批量删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('批量删除失败', error)
    }
  }).catch(() => {})
}

// 处理导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

onMounted(() => {
  loadData()
  getStatisticsData()
  getMemberLevelsData()
  getChartData()
})
</script>

<style lang="scss" scoped>
.app-container {
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .chart-container {
    margin-bottom: 20px;
    
    .chart-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
      gap: 20px;
      
      .chart-card {
        background: var(--el-bg-color-overlay);
        border-radius: var(--el-border-radius-base);
        box-shadow: var(--el-box-shadow-lighter);
        padding: 20px;
        
        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          
          .chart-title {
            font-size: 16px;
            font-weight: bold;
            color: var(--el-text-color-primary);
          }
        }
        
        .chart-content {
          height: 300px;
        }
      }
    }
  }
}
</style>